package com.capgemini.simpleappblanche.controller.customer.validator;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.capgemini.simpleappblanche.constant.ValidatorConstant;
import com.capgemini.simpleappblanche.controller.customer.model.SearchCustomer;
import com.capgemini.simpleappblanche.utils.ValidatorTools;

public class SearchCustomerValidator implements Validator {

	/**
     * {@inheritDoc}
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> clazz) {
        return SearchCustomer.class.isAssignableFrom(clazz);
    }

	/**
	 * {@inheritDoc}
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	@Override
    public void validate(Object target, Errors errors) {
		SearchCustomer form = (SearchCustomer) target;
        
		// checks id
        if (StringUtils.hasText(form.getId()) && !ValidatorTools.isNumeric(form.getId())) {
            errors.rejectValue("id", ValidatorConstant.KEY_NUMERIC, 
            		new Object[] {}, "Id must be numeric");
        }
        
        //check that one data for filter has been filled
        if(!(
        	StringUtils.hasText(form.getId()) ||
        	StringUtils.hasText(form.getName()) ||
        	form.getAgencyId() != null)
        	){
        	errors.reject("customers.search.field.data.required", new Object[] {}, "One data for filter is required");
        }
        			
	}

}
